import 'package:audio_session/audio_session.dart';
import 'package:brage/brage.dart';
import 'package:common_utils/common_utils.dart';
import 'package:fate_blind_box/config/event_bus.dart';
import 'package:fate_blind_box/config/event_keys.dart';
import 'package:flutter/foundation.dart';
import 'package:get/get.dart';
import 'package:im_flutter_sdk/im_flutter_sdk.dart';
import 'state.dart';

class SystemChatMessageLogic extends GetxController {
  final SystemChatMessageState state = SystemChatMessageState();

  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();
    if(Get.arguments!=null){
      state.conversationId = Get.arguments;
    }
    initHuanXinData();
  }

  /// 根据指定会话 ID 和会话类型获取会话对象。
  initHuanXinData() async {
    try {
      // 根据会话id获取当前会话
      EMConversation? conversation =
      await EMClient.getInstance.chatManager.getConversation(
        state.conversationId,
        type: EMConversationType.Chat,
        createIfNeed: true,
      );
      state.conversation = conversation;
      setBrage();
      // 加载当前会话的所有本地消息
      List<EMMessage>? list = await conversation?.loadMessages();
      if (list != null && list.isNotEmpty) {
        state.messageList.addAll(list);
        state.messageList.refresh();
      }
    } on EMError catch (e) {
      if (kDebugMode) {
        print('${e}');
      }
    }
  }

  /// 添加消息监听
  addEventHandler() {
    EMClient.getInstance.chatManager.addEventHandler(
      // EMChatEventHandler 对应的 key。
      "YXA6hl6vye2MTQOb2k-1mAKAiA",
      EMChatEventHandler(
        onMessagesReceived: (messages) async {
          state.player.setAsset('images/music_reveice.mp3');
          final session = await AudioSession.instance;
          session.configure(const AudioSessionConfiguration.music());
          state.player.play();
          getConversation(message: messages);
        },
      ),
    );
  }

  /// 根据会话id 获取当前会话
  getConversation({required List<EMMessage> message}) async {
    for(int i=0;i< message.length;i++){
      if(message[i].conversationId == state.conversationId){
        state.messageList.add(message[i]);
        state.messageList.refresh();
        _addLogToConsole();
        // 将当前消息标记为已读
        await state.conversation?.markMessageAsRead(message[i].msgId);
      }
    }
    setBrage();
  }

  /// 页面跳转
  void _addLogToConsole() {
    state.controller.jumpTo(state.controller.position.maxScrollExtent + 90);
  }

  /// 设置角标
  setBrage(){
    EMClient.getInstance.chatManager.getUnreadMessageCount().then((value){
      Brage().setIOSBrage(brage: value);
      LogUtil.e(tag: '系统消息页面','触发送角标更新');
      EventBus.instance.commit(eventName:EventKeys.chatUpdateBadge,data: value);
    });
  }
  /// 根据index 获取内容
  String getMsgTxt(int index){
    EMMessageBody body = state.messageList[index].body;
    if (body.type == MessageType.TXT) {
      //文字
      var textBody = body as EMTextMessageBody;
      return  textBody.content;
    }else{
      return '';
    }
  }
}
